﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace shopNet
{
    public class Cart : shopNet.ICart
    {
        private Dictionary<product, int> products;
        public Single cost {
            get {
                return products.Keys.Sum(p => (Single)p.Price*products[p]);
            }
        }
        public Cart(shopnetEntities model) {
            _model = model;
            products = new Dictionary<product,int>();
        }
        public void Add(int index, int quantity) {
            var product = _model.products.SingleOrDefault(p=>p.productID == index);
            products.Add(product, quantity);
        }
        public void SetQuantity(int pID, int new_quantity){
            var product = products.Keys.SingleOrDefault(p=>p.productID == pID);
            products[product] = new_quantity;
        }
        public void Delete(int index) {
            var product = products.Keys.SingleOrDefault(p => p.productID == index);
            products.Remove(product);
        }
        public void Show() {
            foreach (var product in products.Keys) {
                Console.WriteLine("Name: {0}, Price: {1}, Quantity: {2}, Cost: {3}", product.name, product.Price, products[product], products[product]*product.Price);
            }
            Console.WriteLine("Total: {0}",this.cost);
        }
        public void Order(Customer cust) {
            var order = cust.Convert();
            order.order_time = DateTime.Now;
            _model.orders.AddObject(order);
            _model.SaveChanges();
            foreach (var prd in products.Keys) {
                var cart_item = new ordered_carts();
                cart_item.orderID = order.orderID;
                cart_item.productID = prd.productID;
                cart_item.Price = prd.Price;
                cart_item.Quantity = products[prd];
                cart_item.name = String.Format("[{0}] {1}",prd.product_code,prd.name);
                _model.ordered_carts.AddObject(cart_item);
            }
            _model.SaveChanges();
        }
        public void Load(int id) {
            var products = _model.ordered_carts.Where(o => o.orderID == id);
            var ids = new Dictionary<int,int>();
            foreach (var ord in products) {
                ids.Add(ord.productID,(int)ord.Quantity);
            }
            foreach (var i in ids.Keys) {
                this.products.Add(_model.products.SingleOrDefault(p => p.productID == i), ids[i]);
            }
        }
    }
}
